package org.itzixi.netty.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.Properties;

public class JedisPoolUtils {

    private static final Properties properties = PropertiesUtils.getInstance();
    private static volatile Jedis jedis;



    private JedisPoolUtils(){

    }

    public static Jedis getJedis(){
        if (jedis == null){
            synchronized (JedisPoolUtils.class){
                if (jedis == null){
                    jedis = initJedisPool().getResource();
                }
            }
        }
        return jedis;
    }

    private static JedisPool initJedisPool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        int maxTotal = Integer.parseInt(properties.getProperty("redis.maxTotal"));
        int maxIdle = Integer.parseInt(properties.getProperty("redis.maxIdle"));
        int minIdle = Integer.parseInt(properties.getProperty("redis.minIdle")) ;
        long maxWait = Long.parseLong(properties.getProperty("redis.maxWait"));
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxWait(Duration.ofSeconds(maxWait));


        String serverAddr = properties.getProperty("server.addr");
        String password = properties.getProperty("redis.password");
        int port = Integer.parseInt(properties.getProperty("redis.port"));
        int timeout = Integer.parseInt(properties.getProperty("redis.timeout"));
        int database = Integer.parseInt(properties.getProperty("redis.database"));
        return new JedisPool(jedisPoolConfig, serverAddr,  port, timeout, password, database);
    }


}
